import RPi.GPIO as GPIO
import time


GPIO.setmode(GPIO.BOARD)
servo_pin = 7

# 设置舵机控制引脚为输出模式
GPIO.setup(servo_pin, GPIO.OUT)

# 设置PWM频率为50Hz（标准舵机频率）
pwm = GPIO.PWM(servo_pin, 50)

# 启动PWM，初始占空比为0（舵机中立位置）
pwm.start(0)

def set_angle(angle):
    # 将角度转换为占空比
    duty = 2 + (angle / 18)
    GPIO.output(servo_pin, True)
    pwm.ChangeDutyCycle(duty)
    time.sleep(1)
    GPIO.output(servo_pin, False)
    pwm.ChangeDutyCycle(0)


try:
    while True:

        set_angle(55)
        time.sleep(5)


        set_angle(83)
        time.sleep(5)


        set_angle(112)
        time.sleep(5)


        set_angle(140)
        time.sleep(5)

except KeyboardInterrupt:
    pass

# 停止PWM
pwm.stop()

# 清理GPIO设置
GPIO.cleanup()
